package com.xy.p2p.service.impl;


import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xy.common.page.Pagination;
import com.xy.common.util.EmailTools;
import com.xy.core.service.impl.BaseServiceImpl;
import com.xy.core.util.BeanUtil;
import com.xy.core.util.DateUtil;
import com.xy.p2p.dao.TfinanceinfoDao;
import com.xy.p2p.dao.TmemberassetaccountDao;
import com.xy.p2p.dao.TmemberassetaccountdetailsDao;
import com.xy.p2p.dao.TtenderrecordDao;
import com.xy.p2p.model.Tfinanceinfo;
import com.xy.p2p.model.Tmember;
import com.xy.p2p.model.Tmemberassetaccount;
import com.xy.p2p.model.Tmemberassetaccountdetails;
import com.xy.p2p.model.Tmembercredit;
import com.xy.p2p.model.Ttenderrecord;
import com.xy.p2p.service.TfinanceinfoService;
import com.xy.p2p.service.TtenderrecordService;

@Service
@Transactional
public class TtenderrecordServiceImpl extends BaseServiceImpl<Ttenderrecord> implements
		TtenderrecordService {
	private TtenderrecordDao ttenderrecordDao;
	@Autowired
	private TmemberassetaccountDao tmemberassetaccountDao;
	@Autowired
	private TmemberassetaccountdetailsDao tmemberassetaccountdetailsDao;
	@Autowired
	private TfinanceinfoDao tfinanceinfoDao;
	@Autowired
	private TfinanceinfoService tfinanceinfoService;
	public TtenderrecordServiceImpl(TtenderrecordDao paramAppRoleDao) {
		super(paramAppRoleDao);
		this.ttenderrecordDao = paramAppRoleDao;
	}

	@Override
	public boolean checkExist(String paraName, String paraValue) {
		return ttenderrecordDao.checkExist("Ttenderrecord", paraName, paraValue);
	}

	@Override
	public List<Ttenderrecord> getTtenderrecord(Map<String, Object> map) {
		return ttenderrecordDao.getTtenderrecord(map);
	}
	@Override
	public Pagination getTtenderrecordByPage(Map<String, Object> map, int pageNo,
			int pageSize) {
		// TODO Auto-generated method stub
		return ttenderrecordDao.getTtenderrecordByPage(map, pageNo, pageSize);
	}
	 
   @Override
	public Ttenderrecord save(Ttenderrecord ttenderrecord) {
//		ttenderrecord.setModtime(new Date());
		if(ttenderrecord.getTrid()==null){
			//新增
        	return super.save(ttenderrecord);
		}else{
			//更新
			Ttenderrecord ttenderrecord1=ttenderrecordDao.get(ttenderrecord.getTrid());
			try {
				BeanUtil.copyNotNullProperties(ttenderrecord1, ttenderrecord);
			} catch (Exception e) {
				e.printStackTrace();
			}  
			return super.save(ttenderrecord1);
		}
	}
   @Override
	public String tender(Ttenderrecord ttenderrecord) {
		Tmember tmember = ttenderrecord.getTmember();
		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("fiid", ttenderrecord.getTfinanceinfo().getFiid());
		Tfinanceinfo tfinanceinfo = tfinanceinfoDao.get(ttenderrecord.getTfinanceinfo().getFiid());
		if (ttenderrecord.getTdmoney() % 50 != 0)
			return "投标金额必须是50的倍数! ";
		if(tmember.getMemberid().equals(tfinanceinfo.getTmember().getMemberid()))
			return "不能投自己发出的标的! ";
		double totalFinanceMoney = tfinanceinfoService.putTenderMoneyIntoEntity(tfinanceinfo).getTotaltendermoney();
		if((tfinanceinfo.getFinanceamount()-totalFinanceMoney)<ttenderrecord.getTdmoney())
			return "输入的投标金额少于该标的可投金额! ";
//		map.clear();
		map.put("Tmember", tmember);
		Tmemberassetaccount account = tmemberassetaccountDao.getTmemberassetaccount(map).get(0);
		if(ttenderrecord.getTdmoney()>account.getBalance())
			return "余额不足! ";
		if(Tmemberassetaccount.ENABLE.equals(account.getStatus().toString())){
			return "账户异常, 请联系网站工作人员.";
		}
//		Tmemberassetaccountdetails tmemberassetaccountdetails = new Tmemberassetaccountdetails(tmember, ttenderrecord.getTdmoney(), -1, 12, new Date(), tfinanceinfo.getFiid().toString(), null);
		account.setBalance(account.getBalance()-ttenderrecord.getTdmoney());
		account.setAmountfrozen(account.getAmountfrozen()+ttenderrecord.getTdmoney());
		account.setAfreason("投标冻结中...");
		tmemberassetaccountDao.save(account);
//		tmemberassetaccountdetailsDao.save(tmemberassetaccountdetails);
		ttenderrecord.setTddatetime(new Date());
		ttenderrecord.setMibmoney(ttenderrecord.getTdmoney());
		ttenderrecordDao.save(ttenderrecord);
		if(totalFinanceMoney+ttenderrecord.getTdmoney()==tfinanceinfo.getFinanceamount()){
			tfinanceinfo.setStatus(4);
			tfinanceinfoDao.save(tfinanceinfo);
		}
		return null;
	}
   
   
   //投标余额贷
   @Override
  	public String tenderYED(Ttenderrecord ttenderrecord) {
  		Tmember tmember = ttenderrecord.getTmember();
  		Map<String, Object> map = new HashMap<String, Object>();
//  		map.put("fiid", ttenderrecord.getTfinanceinfo().getFiid());
  		Tfinanceinfo tfinanceinfo = tfinanceinfoDao.get(ttenderrecord.getTfinanceinfo().getFiid());
//  		if (ttenderrecord.getTdmoney() % 50 != 0)
//  			return "投标金额必须是50的倍数! ";
  		if(tmember.getMemberid().equals(tfinanceinfo.getTmember().getMemberid()))
  			return "不能投自己发出的标的! ";
  		double totalFinanceMoney = tfinanceinfoService.putTenderMoneyIntoEntity(tfinanceinfo).getTotaltendermoney();
//  		if((tfinanceinfo.getFinanceamount()-totalFinanceMoney)<ttenderrecord.getTdmoney())
//  			return "输入的投标金额少于该标的可投金额! ";
//  		map.clear();
  		map.put("Tmember", tmember);
  		Tmemberassetaccount account = tmemberassetaccountDao.getTmemberassetaccount(map).get(0);
  		if(ttenderrecord.getTdmoney()>account.getBalance())
  			return "余额不足! ";
  		if(Tmemberassetaccount.ENABLE.equals(account.getStatus().toString())){
  			return "账户异常, 请联系网站工作人员.";
  		}
//  		Tmemberassetaccountdetails tmemberassetaccountdetails = new Tmemberassetaccountdetails(tmember, ttenderrecord.getTdmoney(), -1, 12, new Date(), tfinanceinfo.getFiid().toString(), null);
  		account.setBalance(account.getBalance()-ttenderrecord.getTdmoney());
  		tmemberassetaccountDao.save(account);
  		Tmemberassetaccountdetails d = new Tmemberassetaccountdetails(tmember, ttenderrecord.getTdmoney(),
  				Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_OUT, Tmemberassetaccountdetails.YED_BORROW_OUT,new Date(), tfinanceinfo.getFiid().toString(), null);
  		tmemberassetaccountdetailsDao.save(d);
  		ttenderrecord.setTddatetime(new Date());
  		ttenderrecord.setMibmoney(ttenderrecord.getTdmoney());
  		ttenderrecordDao.save(ttenderrecord);
  		//增加融资人余额并添加明细
  		Tmember t = tfinanceinfo.getTmember();
  		map.put("Tmember",t);
  		Tmemberassetaccount ac = tmemberassetaccountDao.getTmemberassetaccount(map).get(0);
  		ac.setBalance(ac.getBalance()+ttenderrecord.getTdmoney());
  		tmemberassetaccountDao.save(ac);
  		Tmemberassetaccountdetails tcd = new Tmemberassetaccountdetails(t, ttenderrecord.getTdmoney(), Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_IN, Tmemberassetaccountdetails.YED_BORROW_IN, new Date(), tfinanceinfo.getFiid().toString(), null);
  		tmemberassetaccountdetailsDao.save(tcd);
  		return null;
  	}
   
 //放款的时候发送邮件给投资者
 	@Override
 	public void sendInvestorMail(long trid){
 		// 获取当前标的ID
		Ttenderrecord ttenderrecord = this.get(trid);
		// 获取tmember
		Tmember tmember = ttenderrecord.getTmember();
//		Tmember tmenber1 = 
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(ttenderrecord.getTfinanceinfo().getFiid());
 		//发送主题
 		StringBuffer a = new StringBuffer();
 		a.append("您对“");
 		a.append(ttenderrecord.getTfinanceinfo().getFinancekey());
 		a.append("”的投标已成功！");
 		String subject = a.toString();
 		//发送内容
 		StringBuffer s = new StringBuffer();
 		s.append("尊敬的用户");
 		s.append(tmember.getTruename());
 		s.append("：<br>感谢您对");
 		s.append(tfinanceinfo.getTmember().getLoginname());
 		s.append("的借款列表“");
 		s.append(ttenderrecord.getTfinanceinfo().getFinancekey());
 		s.append("”的帮助与支持。<br>由于该借款列表已成功放款，您的");
 		s.append(ttenderrecord.getTdmoney());
 		s.append("元投标资金已成功转入借款人账户。<br>点击");
 		s.append("<a href='http://www.51d1d.com/融资协议.html'>这里</a>");
 		s.append("查看该笔借款的电子借款协议<br>点击");
 		s.append("<a href='http://www.51d1d.com/member/login.jspx");
	 	s.append("' >这里</a>");
 		s.append("查看您的投标记录<br>点击");
 		s.append("<a href='http://www.51d1d.com/member/login.jspx");
	 	s.append("' >这里</a>");;
 		s.append("查看您的资产账户交易明细<br>感谢您对我们的关注与支持！<br>贷一贷<br>注：此邮件由系统自动发送，请勿回复！<br>如果您有任何疑问，请您查看");
 		s.append("<a href='http://www.51d1d.com/help/helpnounExplain.jspx'>帮助</a>");
 		s.append("，或联系客服电话400-1122-363");
 		String content = s.toString();
 		// 发送邮件
 		try {
 			EmailTools.sendHtmlEmail(content, subject, tmember.getEmail());
 		} catch (Exception e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
 	}
 	//还款的时候发送邮件给投资者
 	 	@Override
 	 	public void sendRefundMail(long trid){
 	 		//设置两位小数点
 	 		DecimalFormat df = new DecimalFormat("0.00");
 	 		//设置日期格式
 	 		java.util.Calendar c = java.util.Calendar.getInstance();
 	 		java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyy年MM月dd日");
 	 		// 获取当前标的ID
 			Ttenderrecord ttenderrecord = this.get(trid);
 			// 获取tmember
 			Tmember tmember = ttenderrecord.getTmember();
 			// 获取tfinanceinfo
 			Tfinanceinfo tfinanceinfo = ttenderrecord.getTfinanceinfo();
 	 		Date today = tfinanceinfo.getNrdate();
 	 		Date molecule = tfinanceinfo.getItfdate();
 	 		double p = ttenderrecord.getTdmoney() / tfinanceinfo.getFinanceamount();
 	 		Double money = p*(tfinanceinfo.getAlino()+tfinanceinfo.getSubpri());
 	 		//发送主题
 	 		StringBuffer a = new StringBuffer();
 	 		a.append("您收到来自");
 	 		a.append(tfinanceinfo.getTmember().getLoginname());
 	 		a.append("的一笔还款");
 	 		String subject = a.toString();
 	 		//发送内容
 	 		StringBuffer s = new StringBuffer();
 	 		s.append("尊敬的用户");
 	 		s.append(tmember.getTruename());
 	 		s.append("：<br>您好，感谢您对用户");
 	 		s.append(tfinanceinfo.getTmember().getLoginname());
 	 		s.append("发布的借款“");
 	 		s.append(tfinanceinfo.getFinancekey());
 	 		s.append("”的支持与帮助。<br>你于");
 	 		s.append(f.format(c.getTime()));
 	 		s.append("收到来自该用户的一笔还款。正常本息￥");
 	 		s.append(df.format(money));
 	 		s.append("共");
 	 		s.append("（");
 	 		s.append(DateUtil.getMonthSpace(today, molecule));
 	 		s.append("/");
 	 		s.append(tfinanceinfo.getFinanceallotedtime()/30);
 	 		s.append("）。<br>点击");
 	 		s.append("<a href='http://www.51d1d.com/member/login.jspx");
 	 		s.append("' >这里</a>");
 	 		s.append("查看您的账户资金记录<br>感谢您对我们的关注与支持！<br>贷一贷<br>注：此邮件由系统自动发送，请勿回复！<br>如果您有任何疑问，请您查看");
 	 		s.append("<a href='http://www.51d1d.com/help/helpnounExplain.jspx'>帮助</a>");
 	 		s.append("，或联系客服电话400-1122-363");
 	 		String content = s.toString();
 	 		// 发送邮件
 	 		try {
 	 			EmailTools.sendHtmlEmail(content, subject, tmember.getEmail());
 	 		} catch (Exception e) {
 	 			// TODO Auto-generated catch block
 	 			e.printStackTrace();
 	 		}
 	 	}
}